<template>
	<view class="uni-container">
		<uni-forms ref="form" v-model="formData" :rules="rules" validateTrigger="bind" @submit="submit">
			<uni-forms-item name="nickName" label="用户名" required>
				<uni-easyinput v-model="formData.nickName" :clearable="false" placeholder="请输入用户名" />
			</uni-forms-item>
			<uni-forms-item name="phone" label="手机号">
				<uni-easyinput v-model="formData.phone" :clearable="false" placeholder="请输入手机号" />
			</uni-forms-item>
			<uni-forms-item name="email" label="邮箱">
				<uni-easyinput v-model="formData.email" :clearable="false" placeholder="请输入邮箱" />
			</uni-forms-item>
			<uni-forms-item label="头像" name="avatarUrl">
				<uni-file-picker limit="1" v-model="imgList" file-mediatype="image" mode="grid" return-type="array"
					:image-styles="{'height': '500rpx','width' : '500rpx'}" @delete="iconUrlDelete" @success="success">
				</uni-file-picker>
			</uni-forms-item>
			<!-- <uni-forms-item name="status" label="用户状态">
				<switch v-if="Number(formData.status) < 2" @change="binddata('status', $event.detail.value)"
					:checked="formData.status" :disabled="formDataId === userId" />
				<view v-else class="uni-form-item-empty">{{parseUserStatus(formData.status)}}</view>
				<view v-if="formDataId === userId" class="uni-form-item-tips">请勿禁用当前登录的账号</view>
			</uni-forms-item> -->
			<view class="uni-button-group">
				<button style="width: 100px;" type="primary" class="uni-button"
					@click="submitForm">{{$t('common.button.submit')}}</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;"><button style="width: 100px;"
						class="uni-button">{{$t('common.button.back')}}</button></navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		validator
	} from '@/js_sdk/validator/uni-id-users.js';

	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'user';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}

	export default {
		data() {
			return {
				showPassword: false,
				formData: {
					"nickName": "",
					"phone": undefined,
					"email": undefined,
					"status": true, //默认开启
					"avatarUrl": ""
				},
				imgList: [],
				rules: {
					...getValidator(["nickName", "phone", "email", "avatarUrl"]),
					"status": {
						"rules": [{
							"format": "bool"
						}]
					}
				},
				roles: [],
				userId: "",
				appList: [],
				unknownAppids: []
			}
		},
		onLoad(e) {
			const id = e.id
			this.formDataId = id
			let userInfo = uni.getStorageSync("uni-id-pages-userInfo") || {};
			this.userId = userInfo._id;
			this.getDetail(id)
		},
		methods: {
			/**
			 * 跳转应用管理的 list 页
			 */
			gotoAppList() {
				uni.navigateTo({
					url: '../app/list'
				})
			},
			gotoTagList() {
				uni.navigateTo({
					url: '../tag/list'
				})
			},
			gotoTagAdd() {
				uni.navigateTo({
					url: '../tag/add',
					events: {
						refreshCheckboxData: () => {
							this.$refs.checkboxTags.loadData();
						}
					}
				})
			},
			/**
			 * 切换重置密码框显示或隐藏
			 */
			trigger() {
				this.showPassword = !this.showPassword
			},

			/**
			 * 触发表单提交
			 */
			submitForm(form) {
				this.$refs.form.submit();
			},
			success(e) {
				console.log(e)
				this.formData.avatarUrl = e.tempFilePaths[0]
			},
			iconUrlDelete(e) {
				console.log(e)
			},
			/**
			 * 表单提交
			 * @param {Object} event 回调参数 Function(callback:{value,errors})
			 */
			submit(event) {
				const {
					value,
					errors
				} = event.detail
				// 表单校验失败页面会提示报错 ，要停止表单提交逻辑
				if (errors) {
					return
				}
				console.log('value', value)
				uni.showLoading({
					title: '修改中...',
					mask: true
				})

				// 是否启用功能的数据类型转换， 1 正常， 0 禁用
				if (typeof value.status === "boolean") {
					value.status = Number(!value.status)
				}
				value._id = this.formDataId
				uniCloud.callFunction({
					name: 'update',
					data: {
						dbName: 'user',
						datas: value
					},
					success: res => {
						console.log('res', res)
						uni.hideLoading()
						if (res.result.status == 0) {
							uni.showToast({
								title: '修改成功！',
							})
							uni.navigateBack({
								delta: 1
							})
						}
					}
				})
				// this.$request('update', value).then(() => {
				// 	uni.showToast({
				// 		title: '修改成功'
				// 	})
				// 	const eventChannel = this.getOpenerEventChannel();
				// 	if (eventChannel.emit) eventChannel.emit('refreshData');
				// 	setTimeout(() => uni.navigateBack(), 500)
				// }).catch(err => {
				// 	uni.showModal({
				// 		content: err.message || '请求服务失败',
				// 		showCancel: false
				// 	})
				// }).finally(err => {
				// 	uni.hideLoading()
				// })
			},

			resetPWd(resetData) {
				this.$request('system/user/resetPwd', resetData)
					.then().catch(err => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					}).finally()
			},
			/**
			 * 获取表单数据
			 * @param {Object} id
			 */
			getDetail(id) {
				uni.showLoading({
					mask: true
				})
				db.collection(dbCollectionName)
					.doc(id)
					.get()
					.then((res) => {
						const data = res.result.data[0]
						if (data) {
							if (data.status === undefined) {
								data.status = true
							}
							if (data.status === 1) {
								data.status = true
							}
							if (data.status === 0) {
								data.status = false
							}

							this.formData = Object.assign(this.formData, data);
							this.imgList.push({
								url: this.formData.avatarUrl
							})
							console.log('this.formData', this.imgList)
						}
					}).catch((err) => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					}).finally(() => {
						uni.hideLoading()
					})
			},
			// status 对应文字显示
			parseUserStatus(status) {
				if (status === 0) {
					return '启用'
				} else if (status === 1) {
					return '禁用'
				} else if (status === 2) {
					return '审核中'
				} else if (status === 3) {
					return '审核拒绝'
				} else if (status === 4) {
					return '已注销'
				} else if (typeof status !== "undefined") {
					return '未知'
				} else {
					return '启用'
				}
			}
		},
		computed: {
			unknownAppidsCom() {
				let str = "";
				this.unknownAppids.map((item, index) => {
					str += item;
					if (index !== this.unknownAppids.length - 1) {
						str += "、";
					}
				});
				return str;
			}
		}
	}
</script>

<style>
	.reset-password-btn {
		/* height: 100%; */
		line-height: 36px;
		color: #007AFF;
		text-decoration: underline;
		cursor: pointer;
	}

	.cancel-reset-password-btn {
		color: #007AFF;
		padding-right: 10px;
		cursor: pointer;
	}

	::v-deep .uni-forms-item__label {
		width: 90px !important;
	}

	.uni-forms-item-flex-center-x {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
	}
</style>